import { loginServer } from "@/serviers/loginServer";
import { UserForm } from "@/types/user";
import { getToken, removeToken, setToken } from "@/utils/token";
import { Dispatch, PayloadAction, createSlice } from "@reduxjs/toolkit";

interface User {
	username: string;
	token: string;
	roles: RolesItem[];
}

interface RolesItem {
	menus: MenusItem[];
	name: string;
}

interface MenusItem {
	acl: string;
	name: string;
	path: string;
	order: string;
}

export interface UserState {
	userInfo: object;
	token: string;
	menuList: MenusItem[];
}

const userStore = createSlice({
	name: "user",
	initialState: {
		userInfo: {},
		token: getToken() || "",
		menuList: [] as MenusItem[],
	} as UserState,
	reducers: {
		// 获取token
		setUserToken(state: UserState, action: PayloadAction<string>) {
			state.token = action.payload;
			setToken(state.token);
		},

		// 登出
		logout(state: UserState) {
			removeToken();
			state.token = "";
			// state.menuList = []
			// state.userInfo = {}
		},

		// 获取用户菜单
		setUserMenus(state: UserState, action: PayloadAction<MenusItem[]>) {
			console.log(action.payload, "payload");

			state.menuList = action.payload;
			console.log(state.menuList, "state.menuList");
		},
	},
});

const { setUserToken, logout, setUserMenus } = userStore.actions;

// 获取reducer函数
const userRenducer = userStore.reducer;

const loginAsync = (userform: UserForm) => {
	return async (dispatch: Dispatch<any>) => {
		const res = await loginServer(userform);
        setToken(res.data.token);
		dispatch(setUserToken(res.data.token));
		dispatch(setUserMenus(res.data.roles[0].menus));
		console.log(res.data.roles[0].menus, "menus");
	};
};

export { loginAsync, logout };

export default userRenducer;
